<template>
	<view class="chat-list-container">
		<!-- 顶部导航 -->
		<uni-nav-bar 
			title="消息" 
			:border="false" 
			background-color="#ffffff"
			color="#333333"
		/>
		
		<!-- 会话列表 -->
		<scroll-view scroll-y class="chat-list" @scrolltolower="loadMore">
			<view class="session-item" 
				v-for="session in sessionList" 
				:key="session.id"
				@click="openChat(session)"
			>
				<view class="avatar-container">
					<image 
						:src="getOtherUserAvatar(session)" 
						class="avatar"
						mode="aspectFill"
					/>
					<view v-if="getUnreadCount(session) > 0" class="unread-badge">
						{{ getUnreadCount(session) > 99 ? '99+' : getUnreadCount(session) }}
					</view>
				</view>
				
				<view class="session-info">
					<view class="session-header">
						<text class="username">{{ getOtherUserName(session) }}</text>
						<text class="time">{{ formatTime(session.lastMessageTime) }}</text>
					</view>
					<view class="last-message">
						<text class="message-content">{{ session.lastMessage || '暂无消息' }}</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-if="sessionList.length === 0 && !loading" class="empty-state">
				<image src="/static/images/empty-chat.png" class="empty-image" />
				<text class="empty-text">暂无聊天记录</text>
			</view>
			
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<uni-load-more :status="loadingStatus" />
			</view>
		</scroll-view>
	</view>
</template>

<script>
import chatApi from '@/api/chat.js'

export default {
	data() {
		return {
			sessionList: [],
			loading: false,
			loadingStatus: 'more',
			currentUser: null
		}
	},
	
	onLoad() {
		this.init()
	},
	
	onShow() {
		this.loadSessions()
	},
	
	onUnload() {
		// 移除事件监听
		uni.$off('chat-sessions-updated', this.handleSessionsUpdated)
		uni.$off('chat-new-message', this.handleNewMessage)
		uni.$off('chat-unread-count-changed', this.handleUnreadCountChanged)
	},
	
	methods: {
		async init() {
			// 获取当前用户信息
			this.currentUser = uni.getStorageSync('userInfo')
			
			// 监听聊天相关事件
			uni.$on('chat-sessions-updated', this.handleSessionsUpdated)
			uni.$on('chat-new-message', this.handleNewMessage)
			uni.$on('chat-unread-count-changed', this.handleUnreadCountChanged)
			
			// 加载会话列表
			this.loadSessions()
		},
		
		async loadSessions() {
			try {
				this.loading = true
				// 优先从聊天管理器获取会话列表
				this.sessionList = this.$chat.getSessions()
				
				// 如果聊天管理器中没有数据，则从API加载
				if (this.sessionList.length === 0) {
					const response = await chatApi.getUserSessions()
					if (response.code === 200) {
						this.sessionList = response.data || []
					}
				}
			} catch (error) {
				console.error('加载会话列表失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		handleSessionsUpdated(sessionList) {
			console.log('会话列表更新:', sessionList)
			this.sessionList = sessionList
		},
		
		handleNewMessage(messageData) {
			console.log('聊天列表收到新消息:', messageData)
			// 会话列表会通过 handleSessionsUpdated 自动更新
		},
		
		handleUnreadCountChanged(unreadCount) {
			console.log('未读消息数变化:', unreadCount)
			// 可以在这里更新UI中的未读消息提示
		},
		
		openChat(session) {
			const otherUserId = this.getOtherUserId(session)
			uni.navigateTo({
				url: `/pages/chat/chatDetail?sessionId=${session.id}&targetUserId=${otherUserId}`
			})
		},
		
		getOtherUserId(session) {
			return this.currentUser.id === session.user1Id ? session.user2Id : session.user1Id
		},
		
		getOtherUserName(session) {
			// 这里需要根据实际情况获取对方用户名
			// 可能需要在会话数据中包含用户信息，或者单独查询
			return this.currentUser.id === session.user1Id ? '用户' + session.user2Id : '用户' + session.user1Id
		},
		
		getOtherUserAvatar(session) {
			// 这里需要根据实际情况获取对方头像
			return '/static/images/default-avatar.png'
		},
		
		getUnreadCount(session) {
			if (this.currentUser.id === session.user1Id) {
				return session.user1UnreadCount || 0
			} else {
				return session.user2UnreadCount || 0
			}
		},
		
		formatTime(timeStr) {
			if (!timeStr) return ''
			
			const time = new Date(timeStr)
			const now = new Date()
			const diff = now - time
			
			// 今天
			if (diff < 24 * 60 * 60 * 1000 && now.getDate() === time.getDate()) {
				return time.toLocaleTimeString('zh-CN', { 
					hour: '2-digit', 
					minute: '2-digit',
					hour12: false 
				})
			}
			
			// 昨天
			const yesterday = new Date(now)
			yesterday.setDate(yesterday.getDate() - 1)
			if (yesterday.getDate() === time.getDate()) {
				return '昨天'
			}
			
			// 更早
			return time.toLocaleDateString('zh-CN', { 
				month: '2-digit', 
				day: '2-digit' 
			})
		},
		
		loadMore() {
			// 暂时不实现分页加载
		}
	}
}
</script>

<style lang="scss" scoped>
.chat-list-container {
	height: 100vh;
	background-color: #f5f5f5;
}

.chat-list {
	height: calc(100vh - 44px);
	background-color: #ffffff;
}

.session-item {
	display: flex;
	padding: 15px;
	border-bottom: 1px solid #f0f0f0;
	background-color: #ffffff;
	
	&:active {
		background-color: #f8f8f8;
	}
}

.avatar-container {
	position: relative;
	margin-right: 12px;
}

.avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	background-color: #f0f0f0;
}

.unread-badge {
	position: absolute;
	top: -5px;
	right: -5px;
	min-width: 18px;
	height: 18px;
	background-color: #ff4d4f;
	border-radius: 9px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
	color: #ffffff;
	padding: 0 4px;
}

.session-info {
	flex: 1;
	min-width: 0;
}

.session-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 5px;
}

.username {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
}

.time {
	font-size: 12px;
	color: #999999;
}

.last-message {
	display: flex;
	align-items: center;
}

.message-content {
	font-size: 14px;
	color: #666666;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100px 20px;
}

.empty-image {
	width: 120px;
	height: 120px;
	margin-bottom: 20px;
}

.empty-text {
	font-size: 16px;
	color: #999999;
}

.loading-state {
	padding: 20px;
}
</style> 